import { useEffect, useState } from 'react'
import styles from './Class.module.css'
import { SearchBar, SideBar, DotLoading, Toast } from 'antd-mobile'
import axios from '../../axios'
import { useSearchParams } from 'react-router-dom'

// 定义类型
interface Tab {
  name: string
}

interface Product {
  id: string
  title: string
  image: string
  currentPrice: number
  originalPrice: number
  sales?: number
  stock?: number
  description?: string
  unit?: string
  category?: string
  tags?: string[]
  activity?: string[]
  status?: string
  createdAt?: string
  updatedAt?: string
}

interface CartItem {
  id: string;
  title: string;
  image: string;
  currentPrice: number;
  originalPrice: number;
  quantity: number;
  category: string;
  tags?: string[];
  activity?: string[];
  stock: number;
  selected: boolean;
}

export default function Class() {
  const [tabs, setTabs] = useState<Tab[]>([])
  const [products, setProducts] = useState<Product[]>([])
  const [activeTab, setActiveTab] = useState<string>('')
  const [loading, setLoading] = useState(false)
  const [searchParams] = useSearchParams()

  // 获取分类
  const getTabs = async () => {
    try {
      const res = await axios.get('http://localhost:3000/jjx/getClassifys')
      setTabs(res.data.data)

      // 获取URL中的category参数
      const categoryFromUrl = searchParams.get('category')

            // 如果URL中有category参数，找到对应的分类
      if (categoryFromUrl) {
        const matchedCategory = res.data.data.find((item: Tab) => item.name === categoryFromUrl)
        if (matchedCategory) {
          setActiveTab(matchedCategory.name)
          getProducts(matchedCategory.name)
          return
        }
      }

      // 如果URL没有category参数或找不到对应分类，使用默认分类
      const defaultCategory = res.data.data.find((item: Tab) => item.name === "时令果蔬")
        if (defaultCategory) {
          setActiveTab(defaultCategory.name)
          getProducts(defaultCategory.name)
        }
    } catch (error) {
      console.error('获取分类失败:', error)
    }
  }

  // 获取商品
  const getProducts = async (categoryName?: string) => {
    if (!categoryName) return
    setLoading(true)
    try {
      const res = await axios.get('http://localhost:3000/jjx/productscategory', {
        params: { category: categoryName }
      })
      // 后端返回的数据结构是直接的数组
      const productsData = Array.isArray(res.data.data) ? res.data.data : []
      // 过滤掉禁用状态的商品
      const activeProducts = productsData.filter((product: Product) => 
        product.status === 'active'
      )
      setProducts(activeProducts)
    } catch (error) {
      console.error('获取商品失败:', error)
      setProducts([]) // 出错时设置为空数组
    } finally {
      setLoading(false)
    }
  }

  // 处理分类切换
  const handleTabChange = (categoryName: string) => {
    if (categoryName === activeTab) return
    setActiveTab(categoryName)
    getProducts(categoryName)
  }

  useEffect(() => {
    getTabs()
  }, [])

  return (
    <div className={styles.pageContainer}>
      <div className={styles.top}>
        <span>分类</span>
        <SearchBar placeholder='请输入内容' />
      </div>
      <div className={styles.container}>
        <div className={styles.sidebar}>
          <SideBar activeKey={activeTab} onChange={handleTabChange}>
            {tabs.map(item => (
              <SideBar.Item key={item.name} title={item.name} />
            ))}
          </SideBar>
        </div>
        <div className={styles.productContainer}>
          {loading ? (
            <div className={styles.loading}>
              <DotLoading />
              <span>加载中...</span>
            </div>
          ) : (
            <div className={styles.productList}>
              {products.map(item => (
                <div key={item.id} className={styles.product}>
                  <div className={styles.imageContainer}>
                    <img src={item.image} alt={item.title} />
                  </div>
                  <div className={styles.contentContainer}>
                    <h3 className={styles.productName}>{item.title}</h3>
                    <div>
                      {
                        item.tags?.map((tag: string, index: number) => (
                          <span key={index} className={styles.tag}>{tag}</span>
                        ))
                      }
                    </div>
                    <div className={styles.priceArea}>
                      <div className={styles.tagArea}>
                        <span className={styles.discount}>已省{(item.originalPrice - item.currentPrice).toFixed(1)}元</span>
                        <span className={styles.limit}>限购5份</span>
                      </div>
                      <div className={styles.priceRow}>
                        <div className={styles.priceInfo}>
                          <span className={styles.currentPrice}>{item.currentPrice}</span>
                          <span className={styles.originalPrice}>¥{item.originalPrice}</span>
                        </div>
                        <button 
                          className={styles.addToCart}
                          onClick={() => {
                            // 添加到购物车
                            const cartItem = {
                              id: item.id,
                              title: item.title,
                              image: item.image,
                              currentPrice: item.currentPrice,
                              originalPrice: item.originalPrice,
                              quantity: 1,
                              category: item.category || '',
                              tags: item.tags || [],
                              activity: item.activity || [],
                              stock: item.stock || 10,
                              selected: true
                            };
                            
                            // 从 localStorage 获取现有购物车
                            const existingCart = localStorage.getItem('cart');
                            const cartItems = existingCart ? JSON.parse(existingCart) : [];
                            
                            // 检查商品是否已在购物车中
                            const existingItemIndex = cartItems.findIndex((cartItem: CartItem) => cartItem.id === item.id);
                            
                            if (existingItemIndex >= 0) {
                              // 如果已存在，增加数量
                              cartItems[existingItemIndex].quantity += 1;
                            } else {
                              // 如果不存在，添加新商品
                              cartItems.push(cartItem);
                            }
                            
                            // 保存到 localStorage
                            localStorage.setItem('cart', JSON.stringify(cartItems));
                            
                            Toast.show('已添加到购物车');
                          }}
                        >
                          加入购物车
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
